class Solution {
public:
    vector<int> searchRange(vector<int>& nums, int target) {
        int n = nums.size();
        vector<int> res(2);
        // 第一个target的位置
        int first = -1;
        // 最后一个target的位置
        int last = -1;

        // 寻找第一个target的位置
        int left = 0;
        int right = n - 1;
        while (left <= right) {
            int mid = (left + right) / 2;
            if (nums[mid] == target) {
                first = mid;
                // 排除当前位置查找前方是否还有值为target的
                right = mid - 1;
            }
            if (nums[mid] < target) {
                left = mid + 1;
            } else if (nums[mid] > target) {
                right = mid - 1;
            }
        }
        res[0] = first;

        // 寻找第二个target的位置
        left = 0;
        right = n - 1;
        while (left <= right) {
            int mid = (left + right) / 2;
            if (nums[mid] == target) {
                last = mid;
                // 排除当前位置查找后方是否还有值为target的
                left = mid + 1;
            }
            if (nums[mid] < target) {
                left = mid + 1;
            } else if (nums[mid] > target) {
                right = mid - 1;
            }
        }
        res[1] = last;
        return res;
    }
};